/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.github.florent37.camerafragment.internal.controller.impl;

import com.github.florent37.camerafragment.configuration.Configuration;
import com.github.florent37.camerafragment.configuration.ConfigurationProvider;
import com.github.florent37.camerafragment.internal.controller.CameraController;
import com.github.florent37.camerafragment.internal.controller.view.CameraView;
import com.github.florent37.camerafragment.internal.manager.CameraManager;
import com.github.florent37.camerafragment.internal.manager.impl.Camera2Manager;
import com.github.florent37.camerafragment.internal.manager.listener.CameraCloseListener;
import com.github.florent37.camerafragment.internal.manager.listener.CameraOpenListener;
import com.github.florent37.camerafragment.internal.manager.listener.CameraPhotoListener;
import com.github.florent37.camerafragment.internal.manager.listener.CameraVideoListener;
import com.github.florent37.camerafragment.internal.ui.view.AutoFitSurfaceView;
import com.github.florent37.camerafragment.internal.utils.CameraHelper;
import com.github.florent37.camerafragment.internal.utils.Log;
import com.github.florent37.camerafragment.internal.utils.Size;
import com.github.florent37.camerafragment.internal.utils.Toast;
import com.github.florent37.camerafragment.listeners.CameraFragmentResultListener;

import ohos.aafwk.ability.fraction.FractionAbility;
import ohos.aafwk.content.Intent;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.graphics.SurfaceOps;
import ohos.app.Context;

import java.io.File;

/**
 * 相机页面控制2
 *
 * @since 2021-03-05
 */
public class Camera2Controller implements CameraController<Integer>,
    CameraOpenListener<Integer, SurfaceOps.Callback>,
    CameraPhotoListener, CameraVideoListener, CameraCloseListener<Integer> {
    private static final String TAG = "Camera2Controller";
    private static final int NEGATIVE = -1;
    private Context context;
    private int currentCameraId;
    private ConfigurationProvider configurationProvider;
    private CameraManager<Integer, SurfaceOps.Callback> camera2Manager;
    private CameraView cameraView;
    private File outputFile;

    /**
     * 构造函数
     *
     * @param context 上下文
     * @param cameraView 相机视图
     * @param configurationProvider 配置项提供者
     */
    public Camera2Controller(Context context, CameraView cameraView, ConfigurationProvider configurationProvider) {
        this.context = context;
        this.cameraView = cameraView;
        this.configurationProvider = configurationProvider;
    }

    @Override
    public void onCreate(Intent stateIntent, DirectionalLayout surfaceProvider, FractionAbility fractionAbility) {
        camera2Manager = new Camera2Manager();
        camera2Manager.initializeCameraManager(configurationProvider, context);
        setCurrentCameraId(camera2Manager.getFaceBackCameraId());
        camera2Manager.initSurfaceComponent(surfaceProvider, fractionAbility, this);
    }

    @Override
    public void onPause() {
        camera2Manager.closeCamera(null);
    }

    @Override
    public void onDestroy() {
        camera2Manager.releaseCameraManager();
    }

    @Override
    public void takePhoto(CameraFragmentResultListener callback) {
        takePhoto(callback, null, null);
    }

    @Override
    public void takePhoto(CameraFragmentResultListener callback, String direcoryPath, String fileName) {
        outputFile = CameraHelper.getOutputMediaFile(context, Configuration.MEDIA_ACTION_PHOTO, direcoryPath, fileName);
        camera2Manager.takePhoto(outputFile, this, callback);
    }

    @Override
    public void startVideoRecord() {
        startVideoRecord(null, null);
    }

    @Override
    public void startVideoRecord(String direcoryPath, String fileName) {
        outputFile = CameraHelper.getOutputMediaFile(context, Configuration.MEDIA_ACTION_VIDEO, direcoryPath, fileName);
        camera2Manager.startVideoRecord(outputFile, this);
    }

    @Override
    public void stopVideoRecord(CameraFragmentResultListener callback) {
        camera2Manager.stopVideoRecord(callback);
    }

    @Override
    public boolean isVideoRecording() {
        return camera2Manager.isVideoRecording();
    }

    @Override
    public void switchCamera(final @Configuration.CameraFace int cameraFace) {
        final int cameraId = camera2Manager.getCurrentCameraId();
        final int faceFrontCameraId = camera2Manager.getFaceFrontCameraId();
        final int faceBackCameraId = camera2Manager.getFaceBackCameraId();
        if (cameraFace == Configuration.CAMERA_FACE_REAR && faceBackCameraId != NEGATIVE) { // 后置摄像头
            setCurrentCameraId(faceBackCameraId);
            camera2Manager.closeCamera(this);
        } else if (faceFrontCameraId != NEGATIVE && faceFrontCameraId != cameraId) { // 前置摄像头
            setCurrentCameraId(faceFrontCameraId);
            camera2Manager.closeCamera(this);
        }
    }

    private void setCurrentCameraId(Integer currentCameraId) {
        this.currentCameraId = currentCameraId;
        camera2Manager.setCameraId(currentCameraId);
    }

    @Override
    public void setFlashMode(@Configuration.FlashMode int flashMode) {
        camera2Manager.setFlashMode(flashMode);
    }

    @Override
    public void switchQuality() {
        camera2Manager.closeCamera(this);
    }

    /**
     * 获取相机设备数量
     *
     * @return int整数
     */
    @Override
    public int getNumberOfCameras() {
        return camera2Manager.getNumberOfCameras();
    }

    @Override
    public int getMediaAction() {
        return configurationProvider.getMediaAction();
    }

    @Override
    public void setMediaAction(int mediaAction) {
        configurationProvider.setMediaAction(mediaAction);
        camera2Manager.setMediaAction(mediaAction);
    }

    /**
     * 获取当前相机ID
     *
     * @return int整数
     */
    @Override
    public int getCurrentCameraId() {
        return currentCameraId;
    }

    @Override
    public File getOutputFile() {
        return outputFile;
    }

    @Override
    public CameraManager getCameraManager() {
        return camera2Manager;
    }

    @Override
    public CharSequence[] getVideoQualityOptions() {
        return camera2Manager.getVideoQualityOptions();
    }

    @Override
    public CharSequence[] getPhotoQualityOptions() {
        return camera2Manager.getPhotoQualityOptions();
    }

    @Override
    public void onCameraClosed(Integer closedCameraId) {
        cameraView.releaseCameraPreview();
        camera2Manager.openCamera(context, closedCameraId, this);
    }

    @Override
    public void onCameraOpened(Integer openedCameraId, Size previewSize, SurfaceOps.Callback surfaceCallback) {
        cameraView.updateUiForMediaAction(Configuration.MEDIA_ACTION_UNSPECIFIED);
        cameraView.updateCameraPreview(previewSize, new AutoFitSurfaceView(context, surfaceCallback));
        cameraView.updateCameraSwitcher(camera2Manager.getNumberOfCameras());
    }

    @Override
    public void onCameraOpenError() {
        Log.error(TAG, "相机打开失败");
    }

    @Override
    public void onPhotoTaken(File photoFile, CameraFragmentResultListener callback) {
        cameraView.onPhotoTaken(callback);
    }

    @Override
    public void onPhotoTakeError() {
        Toast.show(context, "拍照失败");
    }

    @Override
    public void onVideoRecordStarted(Size videoSize) {
        cameraView.onVideoRecordStart(videoSize.getWidth(), videoSize.getHeight());
    }

    @Override
    public void onVideoRecordStopped(File videoFile, CameraFragmentResultListener callback) {
        cameraView.onVideoRecordStop(callback);
    }

    /**
     * 打开闪光灯
     */
    @Override
    public void openFlashLight() {
        camera2Manager.setFlashMode(Configuration.FLASH_MODE_ON);
    }

    /**
     * 关闭闪光灯
     */
    @Override
    public void closeFlashLight() {
        camera2Manager.setFlashMode(Configuration.FLASH_MODE_OFF);
    }

    @Override
    public void setScreenRotation(int degrees) {
        camera2Manager.setScreenRotation(degrees);
    }

    @Override
    public void releaseCamera() {
        camera2Manager.releaseCameraResource();
    }

    @Override
    public void openCamera() {
        camera2Manager.openCamera(context, currentCameraId, this);
    }
}
